<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <link href="/css/plugins/datapicker/datepicker3.css" rel="stylesheet">
    <link href="/css/plugins/nouslider/nouislider.css" rel="stylesheet">
    <link href="/css/plugins/nouslider/nouislider.pips.css" rel="stylesheet">
    <link href="/css/plugins/nouslider/nouislider.tooltips.css" rel="stylesheet">
    <style>
        * {
            box-sizing: border-box !important;
        }

        .button-normal {
            background-color: #FFFFFF;
            border-color: #1ab394 !important;
            /*boder: 1px;*/
            color: #1ab394;
        }

        .button-done {
            background-color: #8a9bab;
            border-color: #8a9bab !important;
            /*boder: 1px;*/
            color: white;
        }

        .button-disabled {
            background-color: #cccccc;
            border-color: #cccccc !important;
            color: white;
        }

        .dropdown-menu {
            z-index: 3000 !important;
        }

        #one-day-schedule td {
            text-align: center;
            vertical-align: middle;
            padding: 0;
            margin: 0;
        }

        #one-day-schedule td.alt,
        #one-day-schedule td div.alt {
            position: relative;
        }

        /*#one-day-schedule td.alt:hover {*/
        /*/!*background: blue;*!/*/
        /*/!*text-decoration: none;*!/*/
        /*z-index: 2;*/
        /*}*/

        /*#one-day-schedule .hover-show {*/
        /*position: absolute;*/
        /*display: block !important;*/
        /*top: -40px;*/
        /*left: 80px;*/
        /*border: 1px solid #c2c2c2;*/
        /*z-index: 1;*/
        /*color: black;*/
        /*background-color: white;*/
        /*opacity: 0.85;*/
        /*font-size: 12px;*/
        /*}*/

        #one-day-schedule td div.alt div.training,
        #one-day-schedule td.alt div.vacation-edit-div {
            display: none;
        }

        #one-day-schedule td div.alt:hover div.training,
        #one-day-schedule td.alt:hover div.vacation-edit-div {
            position: absolute;
            display: block;
            top: -40px;
            left: 50px;
            /*width: 130px;*/
            /*height: 60px;*/
            border: 1px solid darkgrey;
            z-index: 1;
            color: black;
            background-color: white;
            opacity: 0.85;
            /*pointer-events: none;*/
        }

        #one-day-schedule thead tr td {
            height: 36px !important;
        }

        #one-day-schedule tbody tr td {
            height: 55px !important;
        }

        .patient-div {
            text-align: center;
            height: 30px;
            /*width: 30%;*/
            font-size: 12px;
            display: inline-block;
        }

        .td-not-handle {
            background-color: #1ab394;
        }

        .td-not-finish {
            background-color: #97cbff;
        }

        .td-finish {
            background-color: #8a9bab;
        }

        .td-disabled {
            background-color: #cccccc;
        }

        .small-rectangle {
            width: 15px;
            height: 15px;
            display: inline-block;
            vertical-align: middle;
        }

        .small-rectangle-text {
            margin-left: 3px;
            vertical-align: middle;
        }

        #one-day-schedule {
            border-collapse: separate !important;
            cellpadding: 0 !important;
            cellspacing: 0 !important;
        }

        #one-day-schedule td {
            word-break: break-all;
        }

        .noUi-tooltip {
            line-height: 120%;
            padding: 0;
        }
        .ui-jqgrid-hdiv, .ui-jqgrid-hbox, .ui-jqgrid-htable, .ui-jqgrid-bdiv, .ui-jqgrid-btable {
            width: 100% !important;
            padding: 0 !important;
            margin: 0 !important;
        }
    </style>
</head>
<body>

<div class="row">
    <div class="infont col-sm-12 m-b" style="text-align: right;"
         onclick="loadTitle('schedule/group_schedule_title.html')"><a style="cursor:pointer;margin-right: 20px;"><i
            class="fa fa-area-chart"></i>一览表</a></div>
    <div class="col-sm-12" style="padding-bottom: 5px">
        <div class="col-sm-7" style="vertical-align: middle">
            <span id="treatment-group">物理治疗组</span>
        </div>
        <div class="col-sm-3" style="vertical-align: middle">
            <div class="input-group date">
                <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                <input type="text" class="form-control" id="date1-input" readonly="readonly" style="background: white">
            </div>
        </div>
        <div class="col-sm-2" style="vertical-align: middle">
            <select name="select-am-pm" id="select-am-pm"
                    style="padding: 6px;border:1px solid #e7e7e7;box-shadow: none; outline: none;width: 100%;height: 33.9px"
                    onchange="selectAmPm();">
                <option value="am">上午</option>
                <option value="pm">下午</option>
            </select>
        </div>
    </div>
    <div class="col-sm-12">
        <div class="col-sm-12">
            <table class="table table-bordered hide" id="one-day-schedule"
                   style="text-align: center;table-layout: fixed" width="80%">
                <thead id="one-day-schedule-thead">
                <tr>
                    <td width="7.6%">治疗师</td>
                    <td width="15.4%"><span>08:00-08:30</span></td>
                    <td width="15.4%"><span>08:35-09:05</span></td>
                    <td width="15.4%"><span>09:10-09:40</span></td>
                    <td width="15.4%"><span>09:45-10:15</span></td>
                    <td width="15.4%"><span>10:20-10:50</span></td>
                    <td width="15.4%"><span>10:55-11:25</span></td>
                    <td width="13%"><span>13:00-13:30</span></td>
                    <td width="13%"><span>13:35-14:05</span></td>
                    <td width="13%"><span>14:10-14:40</span></td>
                    <td width="13%"><span>14:45-15:15</span></td>
                    <td width="13%"><span>15:20-15:50</span></td>
                    <td width="13%"><span>15:55-16:25</span></td>
                    <td width="13%"><span>16:30-17:00</span></td>
                </tr>
                </thead>
                <tbody id="one-day-schedule-tbody">
                </tbody>
            </table>
            <div class="row">
                <div class="col-sm-3"></div>

                <div class="col-sm-3" style="text-align: center;"><i class="fa fa-star-o"></i><span
                        class="small-rectangle-text">已取消训练</span></div>
                <div class="col-sm-3" style="text-align: center;"><i class="fa fa-star"
                                                                     style="color: #1ab394;"></i><span
                        class="small-rectangle-text">已完成训练</span></div>

                <!--<div class="col-sm-3"></div>-->
                <!--&lt;!&ndash;<div class="col-sm-3" style="text-align: center;"><img class="small-rectangle td-gauge" src="/img/schedule/schedule-gauge.png"><span class="small-rectangle-text">评估</span></div>&ndash;&gt;-->
                <!--&lt;!&ndash;<div class="col-sm-3" style="text-align: center;"><i class="fa fa-user-md"></i><span class="small-rectangle-text">训练</span></div>&ndash;&gt;-->
            </div>
            <div class="row" style="margin-top: 10px;">
                <div class="col-sm-9" style="">提示：每节课30分钟，间隔5分钟</div>
                <div class="col-sm-3" style="">
                    <button class="btn btn-w-m btn-primary inline-block" style="width: 102px;float: right;"
                            onclick="$('#modal-add-vacation-div').modal('show');buildAddVacationDiv();">
                        标记休假
                    </button>
                </div>
            </div>
        </div>

        <div class="col-sm-12">
            <form class="form-horizontal">
                <div class="ibox">
                    <div class="ibox-title">
                        <h5>康复训练患者列表</h5>

                        <div class="ibox-content no-padding" style="border-top: none">
                            <div class="row" style="padding: 8px 0 0 0;">
                                <div class="col-sm-4">
                                    <div class="input-group" style="padding: 0">
                                        <!--<input type="text" class="form-control" id="search-key" placeholder="请输入患者编号进行筛选" oninput="search();">-->
                                        <input type="text" class="form-control" id="search-key" placeholder="患者编号 | 姓名">
                                    <span class="input-group-btn" style="line-height: 34px;">
                                    <button type="button" class="btn btn-primary" onclick="search();">搜索</button>
                                    </span>
                                    </div>
                                </div>
                                <div class="col-sm-3 col-sm-offset-5" style="">
                                    <select onchange="changeSearchStatus(this);" class="form-control m-b"
                                            id="patient-select" name="patient-select">
                                        <option value="">全部患者</option>
                                        <option value="0">未安排康复训练患者</option>
                                        <option value="1">已安排康复训练患者</option>
                                    </select>
                                </div>
                            </div>
                            <!--<select class="form-control" style="padding-top: 0;padding-bottom: 0;height: 25px;"-->
                            <!--onchange="changeSearchStatus(this);">-->
                            <!--<option value="">全部患者</option>-->
                            <!--<option value="0">未安排康复训练患者</option>-->
                            <!--<option value="1">已安排康复训练患者</option>-->
                            <!--</select>-->
                        </div>
                    </div>
                    <div class="ibox-content">
                        <div class="row">

                            <div class="jqGrid_wrapper" id="my-patient-list" style="text-align: center;width: 100%;">
                                <div id="scheduling-div" style="text-align: center;width: 100%;">
                                    <table id="my-patient" style="text-align: center;width: 100%;"></table>
                                </div>

                                <div id="no-records">没有查询记录！</div>
                                <div class="pagination" id="pagination">
                                    <a class="first" id="first-btn-3" data-action="first"><i class="icon-double-angle-left"></i></a>
                					<a class="previous" id="previous-btn-3" data-action="previous"><i class="icon-angle-left"></i></a>
                					<input id="page-num-3" type="text" onkeydown="designatedPage(event, 2)"/>
               						<a class="next" id="next-btn-3" data-action="next"><i class="icon-angle-right"></i></a>
                					<a class="last" id="last_btn_3" data-action="last"><i class="icon-double-angle-right"></i></a>
                                </div>
                            </div>

                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
    <div id="modal-schedule-div" class="row modal fade" aria-hidden="true">
        <div class="col-sm-12">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-body" style="text-align: center;clear:both;border: 1px solid black;">
                        <div class="ibox">
                            <!--<div class="ibox-title">-->
                            <h5 style="text-align: center;clear:both;font-size: 16px;font-weight: bold;">选择时间</h5>
                            <!--</div>-->
                            <div class="ibox-content" style="border: none;">
                                <div class="form-group" id="data">
                                    <div class="row">
                                        <label class="col-sm-2 control-label"
                                               style="font-size: 14px;font-weight: bold;">治疗师</label>

                                        <div class="col-sm-10">
                                            <select class="form-control m-b" id="therapists">
                                            </select>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <label class="col-sm-2 control-label"
                                               style="font-size: 14px;font-weight: bold;">训练日期</label>

                                        <div class="col-sm-10">
                                            <div class="m-b">
                                                <div class="input-group date">
                                                    <span class="input-group-addon"><i
                                                            class="fa fa-calendar"></i></span>
                                                    <input type="text" class="form-control" value="" id="date-input"
                                                           readonly="readonly" style="background: white">
                                                </div>
                                            </div>
                                            <div style="text-align: center;">
                                                <div id="time-block-button" style="min-height: 300px;">
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="m-b" id="weeks-selector">
                                        <label class="m-b-lg">连续排课(周数)</label>

                                        <div id="basic_slider"></div>
                                    </div>


                                    <div class="">
                                        <div class="col-sm-6">
                                            <button data-dismiss="modal"
                                                    class="btn btn-w-m btn btn-default inline-block element-center"
                                                    style="width: 102px;">
                                                取消
                                            </button>
                                        </div>
                                        <div class="col-sm-6">
                                            <button onclick="submit()"
                                                    class="btn btn-w-m btn-primary inline-block element-center"
                                                    style="width: 102px;">
                                                确定
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>


                    </div>


                </div>
            </div>
        </div>
    </div>

    <div id="modal-schedule-div1" class="row modal fade" aria-hidden="true">
        <div class="col-sm-12">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-body" style="text-align: center;clear:both;border: 1px solid black;">
                        <div class="ibox">
                            <!--<div class="ibox-title">-->
                            <h5 style="text-align: center;clear:both;font-size: 16px;font-weight: bold;">选择时间</h5>
                            <!--</div>-->
                            <div class="ibox-content" style="border: none;">
                                <div class="form-group" id="data1">
                                    <div class="row">
                                        <label class="col-sm-2 control-label"
                                               style="font-size: 14px;font-weight: bold;">治疗师</label>

                                        <div class="col-sm-10">
                                            <select class="form-control m-b" id="therapists1">
                                            </select>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <label class="col-sm-2 control-label"
                                               style="font-size: 14px;font-weight: bold;">训练日期</label>

                                        <div class="col-sm-10">
                                            <div class="m-b">
                                                <div class="input-group date">
                                                    <span class="input-group-addon"><i
                                                            class="fa fa-calendar"></i></span>
                                                    <input type="text" class="form-control" value="" id="date-input1"
                                                           readonly="readonly" style="background: white">
                                                </div>
                                            </div>
                                            <div style="text-align: center;">
                                                <div id="time-block-button1" style="min-height: 300px;">
                                                </div>
                                            </div>
                                        </div>
                                    </div>




                                    <div class="">
                                        <div class="col-sm-6">
                                            <button data-dismiss="modal"
                                                    class="btn btn-w-m btn btn-default inline-block element-center"
                                                    style="width: 102px;">
                                                取消
                                            </button>
                                        </div>
                                        <div class="col-sm-6">
                                            <button onclick="submit2()"
                                                    class="btn btn-w-m btn-primary inline-block element-center"
                                                    style="width: 102px;">
                                                确定
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>


                    </div>


                </div>
            </div>
        </div>
    </div>

    <div id="modal-add-vacation-div" class="row modal fade" aria-hidden="true">
        <div class="col-sm-12">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-body" style="text-align: center;clear:both;border: 1px solid black;">
                        <div class="ibox" style="margin: 0">
                            <!--<div class="ibox-title">-->
                            <!--<h5 style="text-align: center;clear:both;font-size: 16px;font-weight: bold;">选择患者</h5>-->
                            <!--</div>-->
                            <div class="ibox-content" style="border: none;">
                                <h5 style="text-align: center;clear:both;font-size: 16px;font-weight: bold;margin-bottom: 25px">
                                    添加休假</h5>

                                <div class="form-group" id="add-vacation">
                                    <div style="text-align: center;height: 30px;font-size: 14px;">
                                        <div class="col-sm-1" style="line-height: 30px;"></div>
                                        <div class="col-sm-11" style="text-align: center;vertical-align: middle;">
                                            <label class="col-sm-3 control-label">标题</label>

                                            <div class="col-sm-9 m-b">
                                                <input type="text" class="form-control" id="vacation-remark"
                                                       maxlength="15">
                                            </div>
                                        </div>
                                    </div>

                                    <div style="text-align: center;height: 30px;font-size: 14px;">
                                        <div class="col-sm-1" style="line-height: 30px;"></div>
                                        <div class="col-sm-11" style="text-align: center;vertical-align: middle;">
                                            <label class="col-sm-3 control-label">治疗师</label>

                                            <div class="col-sm-9 m-b">
                                                <select class="form-control" id="vacation-medical">

                                                </select>
                                            </div>
                                        </div>
                                    </div>

                                    <div style="text-align: center;height: 30px;font-size: 14px;">
                                        <div class="col-sm-1" style="line-height: 30px;"></div>
                                        <div class="col-sm-11" style="line-height: 30px;">
                                            <label class="col-sm-3 control-label">类型</label>

                                            <div class="col-sm-9 m-b" style="text-align: left;">
                                                <input type="checkbox" class="i-checks" id="vacation-type"> 全天
                                            </div>
                                        </div>
                                    </div>

                                    <div style="text-align: center;height: 30px;font-size: 14px;">
                                        <div class="col-sm-1" style="line-height: 30px;"></div>
                                        <div class="col-sm-11" style="line-height: 30px;">
                                            <label class="col-sm-3 control-label">日期
                                            </label>

                                            <div class="col-sm-9 m-b-lg">
                                                <input type="text" class="form-control" id="vacation-date" readonly
                                                       style="background: white">
                                            </div>
                                        </div>
                                    </div>

                                    <div style="text-align: center;height: 30px;font-size: 14px;">
                                        <div class="col-sm-1" style="line-height: 30px;"></div>
                                        <div class="col-sm-11" style="line-height: 30px;">
                                            <label class="col-sm-3 control-label">时间</label>

                                            <div class="col-sm-9 m-b">
                                                <div id="vacation-time-slider"></div>
                                            </div>
                                        </div>
                                    </div>

                                    <div style="text-align: center;height: 30px;font-size: 14px;">
                                        <div class="col-sm-1" style="line-height: 30px;"></div>
                                        <div class="col-sm-11" style="line-height: 30px;">
                                            <label class="col-sm-3 control-label">重复
                                            </label>

                                            <div class="col-sm-9 m-b">
                                                <select class="form-control m-b" id="vacation-repeat-choose"
                                                        name="patient-choose">
                                                    <option value="0">不重复</option>
                                                    <option value="1">每周</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row" style="margin-top: 30px;">
                                        <div class="col-sm-6">
                                            <button data-dismiss="modal"
                                                    onclick="$('#modal-add-vacation-div').modal('hide');"
                                                    class="btn btn-w-m btn btn-white inline-block element-center"
                                                    style="width: 102px;">
                                                取消
                                            </button>
                                        </div>
                                        <div class="col-sm-6">
                                            <button onclick="addVacation()" id="vacation-btn"
                                                    class="btn btn-w-m btn-primary inline-block element-center"
                                                    style="width: 102px;">
                                                确定
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div id="therapist-confirm-div" class="row modal fade" aria-hidden="true">
    <div class="col-sm-12">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-body">
                    <div class="row margin-left-1 m-t m-b-xl" style="text-align: center">
                        确认修改治疗师？
                    </div>

                    <div class="row">
                        <!--<div class="col-sm-6 element-center">-->
                        <button data-dismiss="modal" onclick="cancelSetTherapist();"
                                class="btn btn-w-m btn btn-default inline-block element-center col-sm-3 col-sm-offset-2">
                            取消
                        </button>
                        <!--</div>-->
                        <!--<div class="col-sm-6 element-center">-->
                        <button onclick="setTherapist()"
                                class="btn btn-w-m btn-primary inline-block element-center col-sm-3 col-sm-offset-2">
                            确定
                        </button>
                        <!--</div>-->
                    </div>
                </div>


            </div>
        </div>
    </div>
</div>

<div id="modal-choose-patient-div" class="row modal fade" aria-hidden="true">
    <div class="col-sm-12">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-body" style="text-align: center;clear:both;border: 1px solid black;">
                    <div class="ibox" style="margin:0">
                        <!--<div class="ibox-title">-->
                        <!--<h5 style="text-align: center;clear:both;font-size: 16px">选择患者</h5>-->
                        <!--</div>-->
                        <div class="ibox-content" style="border: none;">
                            <h5 style="text-align: center;clear:both;font-size: 16px;margin-bottom: 25px">选择患者</h5>

                            <div class="form-group" id="data-patient">
                                <div style="text-align: center;height: 30px;font-size: 14px;">
                                    <div class="col-sm-2" style="line-height: 30px;"></div>
                                    <div class="col-sm-7" style="text-align: center;vertical-align: middle;">
                                        <select class="form-control m-b" id="patient-choose" name="patient-choose"
                                                onchange="changePatient('patient-choose')">
                                            <option value="0">请选择患者</option>
                                        </select>
                                    </div>
                                    <div class="col-sm-3" style="line-height: 30px;">
                                        <input type="checkbox" class="i-checks" onchange="filterPatient2()"
                                               id="patient-checkbox">未安排患者
                                    </div>
                                </div>

                                <div class="row" style="margin-top: 30px;">
                                    <div class="col-sm-6">
                                        <button data-dismiss="modal"
                                                class="btn btn-w-m btn btn-white inline-block element-center"
                                                style="width: 102px;">
                                            取消
                                        </button>
                                    </div>
                                    <div class="col-sm-6">
                                        <button onclick="popScheduleModal('patient-choose')"
                                                class="btn btn-w-m btn-primary inline-block element-center"
                                                style="width: 102px;">
                                            确定
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="/js/plugins/datapicker/bootstrap-datepicker.zh-CN.js"></script>
<script src="/js/plugins/nouslider/nouislider.js"></script>

<script>

    var currentPage = 1;
    var totalPage = 1;
    var pageSize = 10;
    var myPatientDivHtml = $("#scheduling-div");
    var pagination = $('#pagination');
    var noRecords = $("#no-records");
    var therapistId = getCookie("profile_id");
    var buttonContent = $("#time-block-button");
    var buttonContent1 = $("#time-block-button1");
    var dateInput = $("#date-input");
    var dateInput1 = $("#date-input1");
    var date1Input = $("#date1-input");
    var prescriptionItemId = null;
    var treatmentGroupId = null;
    var patientId = null;
    var arrangedTimes = 0;//已经安排的还没有完成的任务
    var residueTimes = 0;//剩余次数
    var prcpItemId = null;
    var selectedTherapistId = null;
    var groupMembers;
    var therapists = $("#therapists");
    var therapists1 = $("#therapists1");
    var status = null;
    var startTimeArray = ["08:00", "08:35", "09:10", "09:45", "10:20", "10:55", "13:00", "13:35", "14:10", "14:45", "15:20", "15:55", "16:30"];
    var endTimeArray = ["08:30", "09:05", "09:40", "10:15", "10:50", "11:25", "13:30", "14:05", "14:40", "15:15", "15:50", "16:25", "17:00"];
    var patientChooseHtml = $("#patient-choose");
    var chooseTimeBlockStartDate = "";
    var chooseTimeBlockEndDate = "";
    var amPmSelect = $("#select-am-pm");
    var oneDayScheduleTheadTrs = ("#one-day-schedule-thead tr");

    var selectedTrainingRecordId = null;
    var selectedStartTime = null;
    var selectedEndTime = null;
    var tempTherapistId = null;
    var tempStartTime = null;
    var tempEndTime = null;

    var vacationMedical = $("#vacation-medical");
    var vacationRemark = $("#vacation-remark");
    var vacationRepeat = $("#vacation-repeat-choose");
    var vacationType = $("#vacation-type");
    var vacationDate = $("#vacation-date");
    var timeSlider = document.getElementById('vacation-time-slider');
    var basicSlider = document.getElementById('basic_slider');


    noUiSlider.create(timeSlider, {
                start: [0, 20],
                connect: true,
                step: 1,
                tooltips: [true, true],
                margin: 1,
                range: {
                    'min': 0,
                    'max': 20
                },
                format: {
                    to: function (value) {
                        var hour = parseInt(value / 2) + 8;
                        var min = value % 2 == 0 ? "00" : "30";
                        return hour + ":" + min;
                    },
                    from: function (value) {
                        var v = value.split(":");
                        var hour = parseInt(v[0]);
                        var min = v[1];
                        hour -= 8;
                        if (min == "30") {
                            return hour * 2 + 1;
                        } else {
                            return hour * 2;
                        }


                        return value.replace(',-', '');
                    }
                }
            }
    );

    timeSlider.noUiSlider.on("update", function (value, handle) {
        if (value[0] == "8:00" && value[1] == "18:00") {
            vacationType.prop("checked", true);
        } else {
            vacationType.prop("checked", false);
        }
    });

    vacationType.bind("change", function (event) {

        if ($(event.target).is(':checked')) {
            timeSlider.noUiSlider.set(["8:00", "18:00"]);
        } else {
            timeSlider.noUiSlider.set(["9:00", "17:00"]);
        }
    });

    function changeSearchStatus(event) {
        var val = $(event).val();
        if (val == "") {
            status = null;
        } else {
            status = val;
        }
        currentPage = 1;
        var scrollY = $(document).scrollTop();
        getPrescriptionItemList(1, scrollY);
    }


    pageInit();

    getPrescriptionItemList(1);

    initDatepicker();

    //ios上input,select获取的焦点时position:fixed会失效
    var offsetTop = 0;
    var modalDiv = $("#modal-choose-patient-div,#modal-schedule-div,#therapist-confirm-div,#modal-schedule-div1");
    modalDiv.on('touchmove', function (event) {
        event.preventDefault();
    }, false);
    $(window).scroll(function () {
        offsetTop = document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop;
        modalDiv.attr('style', 'position:absolute;overflow:auto;top:' + offsetTop + "px;");
    });
    modalDiv.on("shown.bs.modal", function () {
        $(".modal-backdrop").attr("style", "position:absolute;top:" + offsetTop + "px;bottom:-" + offsetTop + "px");
    });

    //初始化页面
    function pageInit() {
        pagination.jqPagination({
            max_page: totalPage, //设置最大页 默认为1
            current_page: currentPage, //设置当前页 默认为1
            page_string: '当前第{current_page}页,共{max_page}页',
            paged: function (page) {
                if (page != currentPage) {
                    var scrollY = $(document).scrollTop();
                    currentPage = page;
                    getPrescriptionItemList(2, scrollY);
                }
            }
        });

        // Add responsive to jqGrid
        $("#my-patient-list").bind('resize', function () {
            var width = $('#my-patient-list').width();
            $("#my-patient").setGridWidth(width);
        });

        getTreatmentMembers();

        getTreatmentGroup();

        noUiSlider.create(basicSlider, {
                    start: [1],
                    connect: [true, false],
                    step: 1,
                    tooltips: [true],
                    margin: 1,
                    range: {
                        'min': 0,
                        'max': 10
                    },
                    format: {
                        to: function (value) {
                            return value;
                        },
                        from: function (value) {
                            return value;
                        }
                    }
                }
        
        );
        
    }


    function getTreatmentGroup() {
        mandy_get_my_treat_group_syn(function (data) {
            treatmentGroupId = data.id;
            $("#treatment-group").text(data.name);
        });
    }

    function changeOption(event, itemId, therapistId) {
        $("#therapist-confirm-div").modal("show");
        prcpItemId = itemId;
        selectedTherapistId = therapistId;


    }

    function getTreatmentMembers() {
        mandy_get_treat_group_members_syn(function (data) {
            groupMembers = data.acc_list;
        });

        $.each(groupMembers, function (idx, val) {
            if (!val.disable) {
                addOption(therapists, val.id, val.name);
                addOption(therapists1, val.id, val.name);
                addOption(vacationMedical, val.id, val.name);

                addMemberTr(val.id, val.name);
            }
        });

        therapists.attr("onchange", "buildTimeBlockList(therapists.val(),Date.parse(dateInput.val()));");
        therapists1.attr("onchange", "buildTimeBlockList2(therapists1.val(),Date.parse(dateInput1.val()));");
    }

    function getPrescriptionItemList(option, scrollY) {
        var searchKey = null;
        if (1 == option) {
            $("#search-key").val(null);
        } else {
            searchKey = $("#search-key").val();
        }
        mandy_get_group_prescription_item_list(searchKey, status, currentPage, pageSize, function (data) {
            currentPage = data.current_page;
            totalPage = data.total_page;
            if (totalPage == 0) {
                totalPage = 1;
            }
            pagination.jqPagination('option', 'current_page', currentPage);
            pagination.jqPagination('option', 'max_page', totalPage);

            if (data.list == null) {
                data.list = [];
                noRecords.show();
            }
            else if (data.list.length != 0) {
                noRecords.hide();
            }
            else {
                noRecords.show();
            }

            myPatientDivHtml.empty();
            myPatientDivHtml.append("<table id='my-patient' style='text-align: center;'></table>");

            var index = 1;

            $("#my-patient").jqGrid({
                data: data.list,
                datatype: "local",
                height: "auto",
                autowidth: true,
                shrinkToFit: true,
                rowNum: pageSize,
//                rownumbers: true,
                colNames: ['ID', '序号', '患者编号', '姓名', '性别', '年龄', '类型', '治疗师', '剩余次数', '上一次训练时间', "操作", "查看"],
                colModel: [
                    {name: 'id', index: 'id', width: 0, hidden: true},
                    {
                        name: 'index',
                        index: 'index',
                        width: 40,
                        align: 'center',
                        formatter: function (cellvalue, options, rowObject) {
                            return index++;
                        }
                    },
                    {
                        name: 'prescription.medical_record.number',
                        index: 'prescription.medical_record.number',
                        width: 90,
                        align: 'center',
                        formatter: function (cellvalue, options, rowObject) {
                            return "<span data_my_data=" + rowObject.prescription.medical_record.id + ">" + cellvalue + "</span>";
                        }

                    },
                    {
                        name: 'prescription.medical_record.patient.name',
                        index: 'prescription.medical_record.patient.name',
                        width: 70,
                        align: 'center',
                        formatter: function (cellvalue, options, rowObject) {
                            return "<span data_my_data=" + rowObject.prescription.medical_record.patient.id + ">" + getPrivatePatientName(cellvalue) + "</span>";
                        }
                    },
                    {
                        name: 'prescription.medical_record.patient.sex',
                        index: 'prescription.medical_record.patient.sex',
                        width: 50,
                        align: 'center',
                        formatter: function (cellvalue, options, rowObject) {
                            if (cellvalue == "female") {
                                return "<span data_my_data=" + cellvalue + ">" + "女" + "</span>";
                            }
                            else if (cellvalue == "male") {
                                return "<span data_my_data=" + cellvalue + ">" + "男" + "</span>";
                            }
                            else {
                                return "<span>未知</span>";
                            }
                        }
                    },
                    {
                        name: 'prescription.medical_record.patient.birthday',
                        index: 'prescription.medical_record.patient.birthday',
                        width: 50,
                        align: 'center',
                        formatter: function (cellvalue, options, rowObject) {
                            if (cellvalue != null) {
                                return "<span data_my_data=" + cellvalue + ">" + calculateAge(cellvalue) + "</span>";
                            }
                        }
                    },
                    {
                        name: 'prescription.type', index: 'prescription.type', width: 60, align: 'center',
                        formatter: function (cellvalue, options, rowObject) {
                            if (1 == cellvalue) {
                                return "<span data_my_data=" + cellvalue + ">" + "康复评估" + "</span>";
                            }
                            else {
                                return "<span data_my_data=" + cellvalue + ">" + "康复训练" + "</span>";
                            }
                        }
                    },
                    {
                        name: 'current_therapist', index: 'current_therapist', width: 80, align: 'center',
                        formatter: function (cellvalue, options, rowObject) {
                            var select =
                                    $("<select class='form-control' style='padding: 0;width: 100%;height: 20px;font-size: 12px;'>");
                            select.attr("prcp-item-id", rowObject.id);
                            select.attr("therapist-id", cellvalue.id);

                            select.attr("onchange", 'changeOption(this,"' + rowObject.id + '", this.value)');
//                            select.attr("onchange",'alert(this.value)');

                            $.each(groupMembers, function (idx, therapist) {
                                var option = $("<option>");
                                option.text(therapist.name);
                                option.attr("value", therapist.id);
                                if (therapist.id == cellvalue.id) {

                                    option.attr("selected", true);
                                }
                                select.append(option);
                            });
                            return select.prop("outerHTML");
                        }

                    },
                    {
                        name: 'residue_times', index: 'residue_times', width: 70, align: 'center',
                        formatter: function (cellvalue, options, rowObject) {
                            if (cellvalue != null) {
                                return "<span class='' data_my_data=" + cellvalue + ">" + cellvalue + "</span>";
                            }
                            else {
                                return "<span></span>";
                            }
                        }
                    },
                    {
                        name: 'last_training_time', index: 'last_training_time', width: 120, align: 'center',
                        formatter: function (cellvalue, options, rowObject) {
                            if (cellvalue != null) {
                                var dateTime = getDate(cellvalue).format("YYYY-MM-DD HH:mm");
                                return "<span data_my_data=" + cellvalue + ">" + dateTime + "</span>";
                            }
                            else {
                                return "<span></span>";
                            }
                        }
                    },
                    {
                        name: 'option',
                        index: 'option',
                        width: 60, align: 'center',
                        formatter: function (cellvalue, options, rowObject) {

                            var  schedule = '<a name="schedule" class="schedule_' + rowObject.id + '" data-toggle="modal" href="#modal-schedule-div" style="text-decoration:none;color:#fff;padding:5px 10px;background-color: #36CDEA; border-radius: 14px;">排课</a>';
                            $("#my-patient").on("click",".schedule_" + rowObject.id, function () {
                                handleSchedule(rowObject);
                            });
                            return schedule;
                        }
                    },
                    {
                        name: 'lookup',
                        index: 'lookup',
                        width:60, align: 'center',
                        formatter: function (cellvalue, options, rowObject) {

                            var param = {};
                            param.emr_id = rowObject.prescription.medical_record.id;

                            var a = $("<a>");
                            a.attr("style", "text-decoration:none;color:#fff;padding:5px 10px;background-color: #42D0A7; border-radius: 14px;");
                            a.attr("onclick", "setParamToUrl(" + JSON.stringify(param) + ");loadTitle('/emr/info-title.html');");
                            a.text("病历");
                            return a.prop("outerHTML");
                        }
                    }
                ],
                viewrecords: true,
                hidegrid: false,
                onSelectRow: function (trId, status) {
                }
            });

            if (window.scrollY) {
                window.scroll(0, scrollY);  // reset the scroll position to the top left of the document.
            }
            $("#my-patient tr:even").css("background","#F6F6F6");
        });
    }

    function initDatepicker() {
        dateInput.datepicker({
            defaultDate: getDate().format("yyyy-MM-dd"),
            todayBtn: "linked",
            keyboardNavigation: false,
            forceParse: false,
            calendarWeeks: false,
            autoclose: true,
            language: "zh-CN"
        });

        dateInput.datepicker().on("changeDate", function (e) {
            buildTimeBlockList(therapists.val(), Date.parse(dateInput.val()));
        });


        dateInput.val(new Date().format("yyyy-MM-dd"));

        dateInput1.datepicker({
            defaultDate: new Date().format("yyyy-MM-dd"),
            todayBtn: "linked",
            keyboardNavigation: false,
            forceParse: false,
            calendarWeeks: false,
            autoclose: true,
            language: "zh-CN"
        });

        dateInput1.datepicker().on("changeDate", function (e) {
            buildTimeBlockList2(therapists1.val(), Date.parse(dateInput1.val()));
        });


        dateInput1.val(new Date().format("yyyy-MM-dd"));

        date1Input.datepicker({
            defaultDate: new Date().format("yyyy-mm-dd"),
            todayBtn: "linked",
            keyboardNavigation: false,
            forceParse: false,
            calendarWeeks: false,
            autoclose: true,
            language: "zh-CN"
        });

        date1Input.datepicker().on("changeDate", function (e) {
            getGroupTherapistSchedulePeriods();
        });


        date1Input.val(new Date().format("yyyy-MM-dd"));

        vacationDate.datepicker({
            defaultDate: new Date().format("yyyy-MM-dd"),
//            format:"yyyy-MM-dd",
            todayBtn: "linked",
            keyboardNavigation: false,
            forceParse: false,
            calendarWeeks: false,
            autoclose: true,
            language: "zh-CN"
        });

        vacationDate.val(new Date().format("yyyy-MM-dd"));
    }

    function handleSchedule(obj) {
        therapists.val(obj.current_therapist.id);

//        weeksSelector.removeClass("hide");

        if (obj != null) {
            prescriptionItemId = obj.id;
            if (obj.treatment_group != null) {
                treatmentGroupId = obj.treatment_group.id;
            }
            patientId = obj.prescription.medical_record.patient.id;
            residueTimes = obj.times;
        }
        var date;
        if (obj.last_training_time == null) {
            date = new Date();
        } else {
            // date = getDate(obj.last_training_time);
            date = new Date();
        }

        dateInput.datepicker('setDate', date.format("yyyy-MM-dd"));

//        buildTimeBlockList(therapists.val(), Date.parse(dateInput.val()));

        basicSlider.noUiSlider.on('update', function (values, handle) {
            changeSlider();
        });
    }

    function changeSlider() {
        var selectedButton = buttonContent.find("button.btn-primary").length;
        if (selectedButton == 0) {
            selectedButton = 1;
        }
        var value = basicSlider.noUiSlider.get();
        if (value < 1) {
            basicSlider.noUiSlider.set(1);
        } else if (value * selectedButton > residueTimes) {
            var res = parseInt(residueTimes / selectedButton);
            res = res < 0 ? 1 : res;
            basicSlider.noUiSlider.set(res);
        }
    }

    function handleSchedule2(obj, prcpItemId, pid, gid, day) {

//        if (obj != null) {
        selectedTrainingRecordId = obj.id;
        selectedTherapistId = obj.therapist.id;
        selectedStartTime = obj.start_time;
        selectedEndTime = obj.end_time;
        tempTherapistId = selectedTherapistId;
        tempStartTime = selectedStartTime;
        tempEndTime = selectedEndTime;
        therapists1.val(selectedTherapistId);
        prescriptionItemId = obj.prescription_item.id;
        if (obj.treatment_group != null) {
            treatmentGroupId = obj.treatment_group.id;
        }
        patientId = obj.patient.id;
        residueTimes = obj.prescription_item.times;

        var date = getDate(tempStartTime);

        dateInput1.datepicker('update', date.format("yyyy-MM-dd"));


        buildTimeBlockList2(therapists1.val(), Date.parse(dateInput1.val()));
    }

    function buildTimeBlockList(therapistId, date, canDelete) {
        buttonContent.empty();

        mandy_get_therapist_schedule(therapistId, date, function (data) {
            $.each(data.time_block_list, function (idx, val) {
                var divButton = $("<div class='col-sm-4' style='padding: 0;margin: 0.5vw 0;'>");
                var n = (idx + 1) % 3;
                switch (n) {
                    case 0:
                        divButton.css("text-align", "right");
                        break;
                    case 1:
                        divButton.css("text-align", "left");
                        break;
                    case 2:
                        divButton.css("text-align", "center");
                        break;
                }
                var button = $("<button class='btn' type='button' style='width: 102px !important; height: 34px !important;padding: 0;margin: 0;'>");
//                var button = $("<button class='btn btn-xs m col-sm-3' type='button' style='padding: 0;'>");
                button.prop("id", "time-block-" + (idx + 1));
                button.attr("start_time", val.start_time);
                button.attr("end_time", val.end_time);
                button.attr("record_id", val.record_id);
                button.text(getDate(val.start_time).format("HH:mm") + "-" + getDate(val.end_time).format("HH:mm"));
                button.attr("onclick", "setSelectedTime(this)");

                /**
                 * 时间块状态
                 * 1：已过期并且未安排
                 * 2：已过期并且已安排
                 * 3：已过期并且已安排并且已完成
                 * 4：已过期并且已安排并且已取消
                 *
                 * 5：进行中并且未安排
                 * 6：进行中并且已安排
                 * 7：进行中并且已安排并且已完成
                 * 8：进行中并且已安排并且已取消
                 *
                 * 9： 未过期并且未安排
                 * 10：未过期并且已安排
                 * 11：未过期并且已安排并且已完成
                 * 12：未过期并且已安排并且已取消
                 */

                //6、10
                if (6 == val.status || 10 == val.status) {
                    //当前治疗项目
                    if (val.prescription_item_id != null && val.prescription_item_id == prescriptionItemId) {
                        if (canDelete != null && canDelete == 1) {
                            button.addClass("btn-primary");
                            button.prop("disabled", false);
                        }
                        else {
//                            button.addClass("button-disabled");
//                            button.prop("disabled", true);
                            button.addClass("button-normal");
                            button.prop("disabled", false);
                        }

                    }
                    else {
//                        button.addClass("button-disabled");
//                        button.prop("disabled", true);
                        button.addClass("button-normal");
                        button.prop("disabled", false);
                    }
                }
                //5、9，7，8，11，12
                else if (5 == val.status || 9 == val.status || 7 == val.status || 8 == val.status || 10 == val.status
                        || 11 == val.status || 12 == val.status) {
                    button.addClass("button-normal");
                    button.prop("disabled", false);
                }
                //1，2，3，4
                else {
                    button.addClass("button-disabled");
                    button.prop("disabled", true);
                }

                divButton.append(button);
                buttonContent.append(divButton);
//                buttonContent.append(button);
            });
        });
    }

    function setSelectedTime(event) {
        if ($(event).hasClass("btn-primary")) {
            $(event).removeClass("btn-primary");
            $(event).addClass("button-normal");
        }
        else {
            $(event).addClass("btn-primary");
            $(event).removeClass("button-normal");
        }
        changeSlider();

    }

    function buildTimeBlockList2(therapistId, date) {
        buttonContent1.empty();

        mandy_get_therapist_schedule(therapistId, date, function (data) {
            $.each(data.time_block_list, function (idx, val) {

                var divButton = $("<div class='col-sm-4' style='padding: 0;margin: 0.5vw 0;'>");
                var n = (idx + 1) % 3;
                switch (n) {
                    case 0:
                        divButton.css("text-align", "right");
                        break;
                    case 1:
                        divButton.css("text-align", "left");
                        break;
                    case 2:
                        divButton.css("text-align", "center");
                        break;
                }
                var button = $("<button class='btn' type='button' style='width: 102px !important; height: 34px !important;padding: 0;margin: 0;'>");
                button.prop("id", "time-block-" + (idx + 1));
                button.attr("start_time", val.start_time);
                button.attr("end_time", val.end_time);
                button.attr("record_id", val.record_id);
                button.text(getDate(val.start_time).format("HH:mm") + "-" + getDate(val.end_time).format("HH:mm"));
                button.attr("onclick", "setSelectedTime2(this)");


                if (therapistId == tempTherapistId && val.start_time == tempStartTime) {
                    button.addClass("btn-primary");
                    button.prop("disabled", false);
                } else if (therapistId == selectedTherapistId && val.start_time == selectedStartTime) {
                    button.addClass("button-normal");
                    button.prop("disabled", false);
                }
                //5、9，7，8，11，12，6，10
                else if (5 == val.status || 9 == val.status || 7 == val.status || 8 == val.status || 10 == val.status
                        || 11 == val.status || 12 == val.status || 6 == val.status || 10 == val.status) {
                    button.addClass("button-normal");
                    button.prop("disabled", false);
                }
                //1，2，3，4
                else {
                    button.addClass("button-disabled");
                    button.prop("disabled", true);
                }

                divButton.append(button);
                buttonContent1.append(divButton);
            });
        });
    }

    function setSelectedTime2(event) {
        if ($(event).hasClass("button-normal")) {
            $(event).removeClass("button-normal");
            $(event).addClass("btn-primary");
            if (therapists1.val() == tempTherapistId) {
                $("#time-block-button1 button[start_time='" + tempStartTime + "']").removeClass("btn-primary");
                $("#time-block-button1 button[start_time='" + tempStartTime + "']").addClass("button-normal");
            }
            tempStartTime = $(event).attr("start_time");
            tempEndTime = $(event).attr("end_time");
        } else if ($(event).hasClass("btn-primary")) {
            $(event).removeClass("btn-primary");
            $(event).addClass("button-normal");
            tempStartTime = null;
            tempEndTime = null;
        }
        tempTherapistId = therapists1.val();
    }

    function setTherapist() {
        mandy_set_pcrp_item_therapist(prcpItemId, selectedTherapistId, function (data) {
            toastr.success("修改成功");
            var select = $("select[prcp-item-id='" + prcpItemId + "']");
            select.attr("therapist-id", selectedTherapistId);

            var a = $(select).parent().parent().find("a[name='schedule']");

            var obj = JSON.parse(a.attr("obj"));
            obj.current_therapist = {};
            obj.current_therapist.id = selectedTherapistId;

            a.attr("obj", JSON.stringify(obj));
            a.attr("onclick", "handleSchedule(" + JSON.stringify(obj) + ");");
        });
//        prcpItemId = null;
//        selectedTherapistId = null;
        $("#therapist-confirm-div").modal("hide");


    }

    function cancelSetTherapist() {
        var select = $("select[prcp-item-id='" + prcpItemId + "']");
        select.val(select.attr("therapist-id"));
    }

    function submit() {
        var selectTimeBlockList = buttonContent.children();

        var timeListAdd = [];
        var recordListDel = [];
        $.each(selectTimeBlockList, function (idx, val) {
            val = $(val).children("button")[0];
            if ($(val).hasClass("btn-primary")) {
                var timeBlock = {};
                timeBlock.start_time = $(val).attr("start_time");
                timeBlock.end_time = $(val).attr("end_time");
                timeListAdd.push(timeBlock);
            }

            if ($(val).hasClass("button-normal") && $(val).attr("record_id") != null) {
                recordListDel.push($(val).attr("record_id"));
            }
        });

        if (timeListAdd.length == 0 && recordListDel.length == 0) {
            toastr.error("没有做出任何安排");
            return;
        }

        mandy_post_therapist_schedule(prescriptionItemId, therapists.val(), basicSlider.noUiSlider.get(), timeListAdd, function (data) {
            getPrescriptionItemList(1);
            getGroupTherapistSchedulePeriods();
            toastr.success("添加排课成功");
            $("#modal-schedule-div").modal('hide');
        });
    }


    function submit2() {
        if (selectedTherapistId == tempTherapistId && selectedStartTime == tempStartTime) {
            toastr.error("没有做出任何修改");
            return;
        }
        var timeListAdd = [];
        if (tempStartTime != null) {
            timeListAdd.push({
                start_time: tempStartTime,
                end_time: tempEndTime
            });
        }
        var recordListDel = [selectedTrainingRecordId];

        mandy_put_therapist_schedule(prescriptionItemId, tempTherapistId, patientId, timeListAdd, recordListDel,
                function (data) {
                    getPrescriptionItemList(1);
                    getGroupTherapistSchedulePeriods();
                    toastr.success("修改成功");
                    $("#modal-schedule-div1").modal('hide');
                });
    }


    function addMemberTr(id, name) {
        var tr = $("<tr id='member_" + id + "' m_id='" + id + "'>");

        var td = $("<td><span>" + name + "</span></td>");
        tr.append(td);
        for (var i = 0; i < 13; i++) {
            var td1 = $("<td data-time-block-start='" + startTimeArray[i] + "' data-time-block-end='" + endTimeArray[i] + "'>");
            tr.append(td1);
        }
        $("#one-day-schedule-tbody").append(tr);


    }

    function designatedPage(e, idx) {
        var ev = window.event || e;
        var pageNum = 1;
        var totalPage = 1;
        if (1 == idx) {
            pageNum = $("#page-num-1").val();
            totalPage = totalPage1;
        }
        else if (2 == idx) {
            pageNum = $("#page-num-2").val();
            totalPage = totalPage2;
        }
        else if (3 == idx) {
            pageNum = $("#page-num-3").val();
            totalPage = totalPage3;
        }

        if (ev.keyCode == 13) {
            if (!/^[0-9]*$/.test(pageNum) || pageNum > totalPage || pageNum < 1) {
                toastr.error("请输入正确的页数!");
                return;
            }
        }
    }
    getGroupTherapistSchedulePeriods();
    function getGroupTherapistSchedulePeriods() {
        clearScheduleTbody();
        var startDate = getDate(date1Input.val()).getTime();
        var endDate = startDate + 24 * 3600 * 1000;
        mandy_get_therapist_group_schedule_periods(startDate, endDate, function (data) {
            //清除掉所有的TD 防止重复点击时产生多条重复结果的问题
            $("#one-day-schedule-tbody td[data-time-block-start]").empty();
            if (data.treatment_record_list != null) {
                $.each(data.treatment_record_list, function (idx, val) {
                    buildTaskTd(val);
                });
            }

            fillEmptyTd();
            selectAmPm();
            $("#one-day-schedule").removeClass("hide");

            mandy_get_vacation(null, treatmentGroupId, startDate, endDate, function (data) {
                $.each(data.vacation_list, function (idx, vacation) {
                    var start;
                    var end;
                    start = new Date(vacation.start_time).format("HH:mm");
                    end = new Date(vacation.end_time).format("HH:mm");

                    var tds = $("#member_" + vacation.medical.id + " td");
                    $.each(tds, function (idx, td) {
                        td = $(td);
                        var sStart = td.attr("data-time-block-start");
                        var sEnd = td.attr("data-time-block-end");
                        if (sStart != null && sEnd != null) {
                            if (!(sEnd <= start || sStart >= end)) {
//                                td.text("************");
//                                var divVacationEdit =
//                                        $('<div class="ibox vacation-edit-div" style="width: 250px; height: 50px">');
//                                divVacationEdit.html("休假提示 <br>" + start + "~" + end + "<br>" +
//                                        "<a onclick='$(\"#modal-add-vacation-div\").modal(\"show\");buildUpdateVacationDiv(" + JSON.stringify(vacation) + ",this);'>编辑</a>|<a onclick='delVacation(" + vacation.id + ")'>删除</a>");
                                td.text("休假");
                                clearTdAttr(td);
                                var divForm = $('<div class="ibox-content vacation-edit-div"  style="width:250px; height:110px; border: 1px #cccccc solid;padding-bottom: 0px;padding-left: 10px;padding-right: 10px" id="data-vacation">');
                                var vacationNameDiv = $('<div class="" style="padding-bottom: 10px;">');
                                vacationNameDiv.html("休假提示:" + vacation.remark);

                                var vacationTimeDiv = $('<div class="patient-div" style="">');
                                vacationTimeDiv.text(start + "~" + end);

                                var vacationActDiv = $('<div style="text-align: right;border-top: 1px #cccccc solid; padding-top: 5px;padding-bottom: 10px;">');
                                var btnEdit = $('<span class="" id="btn-edit" style="cursor: pointer;color: #40a6cb;">');
                                btnEdit.text("编辑");
                                btnEdit.attr("onclick", "$(\"#modal-add-vacation-div\").modal(\"show\");buildUpdateVacationDiv(" + JSON.stringify(vacation) + ",this)");
                                var line = $('<span class="" style="margin: 0 2px">');
                                line.text("|");
                                var btnDel = $('<span class="" id="btn-del" style="cursor: pointer;color: #fa9b9b;">');
                                btnDel.text("删除");
                                btnDel.attr("onclick", "delVacation(" + vacation.id + ")");
                                vacationActDiv.append(btnEdit);
                                vacationActDiv.append(line);
                                vacationActDiv.append(btnDel);
                                divForm.append(vacationNameDiv);
                                divForm.append(vacationTimeDiv);
                                divForm.append(vacationActDiv);
                                td.append(divForm);
                                $(td).addClass("alt");
                            }
                        }
                    });

                });
            });
        });


    }

    function buildTaskTd(val) {
        if (typeof(val) == "undefined" || val == null) {
            return;
        }

        var patientId = val.patient.id;
        var patientName = getPrivatePatientName(val.patient.name);
        var patientSex = sexArray[val.patient.sex];
        var patientAge = calculateAge(val.patient.birthday);

        var recordId = val.id;

        //var EMRNum = cutEMRNumber(val.prescription_item.prescription.medical_record.number);
        var EMRNum = val.prescription_item.prescription.medical_record.number;
        var startTime = val.start_time;
        var endTime = val.end_time;
        var status = val.status;

        var totalTimes = val.prescription_item.times;
        var notFinishTimes = val.prescription_item.times - val.prescription_item.execution_times;


        var typeNumber = val.prescription_item.prescription.type;
        var typeName = "";
        var resText = "";
        var prescriptionItemId = "";
        var treatmentGroupId = "";
        var td = null;

        if (1 == typeNumber) {
            resText = val.gauge.name;
            typeName = "康复评估";
            td = getMemberTd(val.medical.id, startTime, "gauge", val.id);
        }
        else {
            prescriptionItemId = val.prescription_item.id;
            treatmentGroupId = val.treatment_group.id;
            resText = "未完成次数/总次数：" + notFinishTimes + "/" + totalTimes;
            typeName = "康复训练";
            td = getMemberTd(val.therapist.id, startTime, "training", val.id);
        }


        if (td != null) {
            var divTdChild = $("<div style='width: 100%;border: 1px solid white'>");

            //悬浮框
            var divBox = $("<div class='ibox' style='width: 250px;'>");
            if (1 == typeNumber) {
                divBox.addClass("gauge");
            }
            else {
                divBox.addClass("training");
                $(td).hoverDelay({
                    hoverEvent: function () {
                        divBox.addClass("hover-show");
                    },
                    outEvent: function () {
                        divBox.removeClass("hover-show");
                    }
                });
            }
            var divContent = $('<div class="ibox-content" style="border: none;padding-bottom: 0px;padding-left: 10px;padding-right: 10px">');
            var divForm = $('<div class="form-group" id="data-patient">');
            var div1 = $('<div class="">');
            var divPatientName = $('<div class="patient-div" style="">');
            divPatientName.html(EMRNum + "&nbsp;&nbsp;&nbsp;&nbsp;" + patientName + "&nbsp;&nbsp;&nbsp;&nbsp;" + patientSex + "&nbsp;&nbsp;&nbsp;&nbsp;" + patientAge);

            var div2 = $('<div style="text-align: center;height: 30px;">');
            var divType = $('<div class="patient-div" style="">');
            divType.text(typeName);
            var divResidueTimes = $('<div style="width: 70%;display: inline-block;">');
            divResidueTimes.text(resText);


            div1.append(divPatientName);
            div2.append(divType);
            div2.append(divResidueTimes);
            divForm.append(div1);
            divForm.append(div2);
            divContent.append(divForm);
            divBox.append(divContent);

            //td顶部
            var topTag = $("<div style='height:18px;width: 100%;'>");
            var divImg1 = $('<div class="" style="text-align: left;padding-left:2px;font-size: 13px;font-weight: bold;width: 80%;display: inline-block;>">');
            divImg1.text(typeName);
            topTag.append(divImg1);

            //病历号 病患名
            var a = $('<a style="color:rgb(103, 106, 108);text-align: left;width:100%;padding-left: 2px;display: block;">');
            var divEMRNumTxt = $('<div style="font-size: 12px;white-space:nowrap;text-overflow:ellipsis; -o-text-overflow:ellipsis;overflow: hidden;">');
            divEMRNumTxt.text(EMRNum);
            var divPatientNameTxt = $('<div style="font-size: 12px;">');
            divPatientNameTxt.text(patientName);
            a.append(divEMRNumTxt, divPatientNameTxt);
            if (1 == status) {
                $(divTdChild).css("background-color", "#f5f4f5");
                var divImg2Container = $("<div style='width: 20%;display: inline-block;'>");
                var divImg2 = $('<i class="fa fa-star" style="color:#1ab394;font-size: 13px;text-align:right;margin-right: 2px;">');
                divImg2Container.append(divImg2);
                topTag.append(divImg2Container);
            }
            else if (2 == status) {
                $(divTdChild).css("background-color", "#f5f4f5");
                var divImg2Container = $("<div style='width: 20%;display: inline-block;'>");
                var divImg2 = $('<i class="fa fa-star-o" style="font-size: 13px;text-align:right;margin-right: 2px;">');
                divImg2Container.append(divImg2);
                topTag.append(divImg2Container);
            }
            else {
                if (typeNumber == 2) {
                    if (new Date() < getDate(date1Input.val() + " " + $(td).attr("data-time-block-end"))) {
                        var div3 = $('<div style="text-align: right;border-top: 1px #cccccc solid; padding-top: 5px;">');
                        var btnEdit = $('<span class="" id="btn-edit" style="cursor: pointer;color: #40a6cb;">');
                        btnEdit.text("编辑");
                        btnEdit.attr("onclick", "$('#modal-schedule-div1').modal('show');handleSchedule2(" + JSON.stringify(val) + ")");
                        var line = $('<span class="" style="margin: 0 2px">');
                        line.text("|");
                        var btnDel = $('<span class="" id="btn-del" style="cursor: pointer;color: #fa9b9b;">');
                        btnDel.text("删除");
                        btnDel.attr("onclick", "del(" + val.id + ")");
                        div3.append(btnEdit);
                        div3.append(line);
                        div3.append(btnDel);
                        divForm.append(div3);
                        a.attr("data-toggle", "modal");
                        a.attr("data-target", "#modal-schedule-div1");
                        a.attr("onclick", "handleSchedule2(" + JSON.stringify(val) + ")");
                    }
                }
                $(divTdChild).css("background-color", "#d6eded");
                var divImg2Container = $("<div style='width: 20%;display: inline-block;'>");
                topTag.append(divImg2Container);
            }

            if(isPc()) {
                $(divTdChild).addClass("alt");
                $(divTdChild).append(topTag, a, divBox);
            }
            else {
                $(divTdChild).append(topTag, a);
            }

            $(td).append(divTdChild);
        }
    }

    function getMemberTd(memberId, startTime, type, id) {
        var date = getDate(startTime);
        var HHMM = date.format("HH:mm");
        var idx = "";
        if (HHMM == "08:00") {
            idx = 1;
        }
        else if (HHMM == "08:35") {
            idx = 2;
        }
        else if (HHMM == "09:10") {
            idx = 3;
        }
        else if (HHMM == "09:45") {
            idx = 4;
        }
        else if (HHMM == "10:20") {
            idx = 5;
        }
        else if (HHMM == "10:55") {
            idx = 6;
        }
        else if (HHMM == "13:00") {
            idx = 7;
        }
        else if (HHMM == "13:35") {
            idx = 8;
        }
        else if (HHMM == "14:10") {
            idx = 9;
        }
        else if (HHMM == "14:45") {
            idx = 10;
        }
        else if (HHMM == "15:20") {
            idx = 11;
        }
        else if (HHMM == "15:55") {
            idx = 12;
        }
        else if (HHMM == "16:30") {
            idx = 13;
        }
        else {
            idx = null;
        }

        if (idx == null) {
            return null;
        }
        return $("#member_" + memberId + " td")[idx];
    }

    function clearScheduleTbody() {
        var trs = $("#one-day-schedule-tbody tr");
        $.each(trs, function (idx, tr) {
            var tds = $(tr).children("td");
            $.each(tds, function (idx, td) {
                if (idx > 0) {
                    $(td).remove();
                    $(tr).append("<td data-time-block-start='" + startTimeArray[idx - 1] + "' data-time-block-end='" + endTimeArray[idx - 1] + "'>");
                }
            })
        });
    }

    function fillEmptyTd() {
        var trs = $("#one-day-schedule-tbody tr");
        var day = date1Input.val();
        $.each(trs, function (idx, tr) {
            var tds = $(tr).children("td");
            $.each(tds, function (idx, td) {
                if (idx != 0) {
                    if ($(td).children("div").length <= 0) {
                        if (new Date() < getDate(day + " " + $(td).attr("data-time-block-end"))) {
                            $(td).attr("onclick", "popChoosePatientModal(this);");
                            $(td).attr("data-toggle", "modal");
                            $(td).attr("data-target", "#modal-choose-patient-div");
                            $(td).css("background-color", "white");
                        }
                        else {
                            $(td).css("background-color", "#white");
                        }
                    }
                }
            });
        });
    }
    function clearTdAttr(e) {
        $(e).attr("onclick", "");
        $(e).attr("data-toggle", "");
        $(e).attr("data-target", "");
        $(e).attr("background-color", "");
    }
    function popChoosePatientModal(e) {
        var day = date1Input.val();
        $("#patient-checkbox").prop("checked", false);
        chooseTimeBlockStartDate = $(e).attr("data-time-block-start");
        chooseTimeBlockEndDate = $(e).attr("data-time-block-end");
        selectedTherapistId = parseInt(($(e).parent().attr("id")).split("_")[1]);
        var time = getDate(day + " " + chooseTimeBlockStartDate).valueOf();
        getPrescriptionItemList2(null, 1, 10000);
    }

    function getPrescriptionItemList2(status, page, pageSize) {
        mandy_get_group_prescription_item_list(null, status, page, pageSize, function (data) {
            patientChooseHtml.empty();
            var option = $("<option value='0'>请选择患者</option>");
            patientChooseHtml.append(option);

            if (data.list == null || data.list.length == 0) {
                return;
            }

            var patientIds = [];

            var newList = [];

            $.each(data.list, function (idx, val) {
                var patientId = "\"" + val.prescription.medical_record.patient.id + "\"";
                if (patientIds[patientId] != null) {
                    if (patientIds[patientId] > val.prescription.create_time) {
                        patientIds[patientId] = val.prescription.create_time;
                        newList[patientId] = val;
                    }
                }
                else {
                    newList[patientId] = val;
                }
            });
            makePatientOption(newList);

        });
    }

    function makePatientOption(list) {
        for (var id in list) {
            var val = list[id];

            var patientId = val.prescription.medical_record.patient.id;
            var prescriptionItemId = val.id;
            var treatmentGroupId = null;
            if (val.treatment_group != null) {
                treatmentGroupId = val.treatment_group.id;
            }
            var patientName = getPrivatePatientName(val.prescription.medical_record.patient.name);
            var EMRNum = val.prescription.medical_record.number;
            var sex = sexArray[val.prescription.medical_record.patient.sex];
            var age = calculateAge(val.prescription.medical_record.patient.birthday);

            var option = $("<option>");
            option.attr("data-prescription-item-id", prescriptionItemId);
            option.attr("data-patient-id", patientId);
            option.attr("data-group-id", treatmentGroupId);
            option.append(EMRNum + "-" + patientName + "-" + sex + "-" + age);
            patientChooseHtml.append(option);
        }
    }

    function del(id) {
        mandy_delete_treatment_record(id, function () {
            toastr.success("删除成功！");
            getGroupTherapistSchedulePeriods();
        });
    }

    function changePatient(id) {
        var obj = $("#" + id + " option:selected");
        prescriptionItemId = obj.attr("data-prescription-item-id");
        treatmentGroupId = obj.attr("data-group-id");
        patientId = obj.attr("data-patient-id");
    }

    function popScheduleModal(id) {
        var day = date1Input.val();
        var timeListAdd = [
            {
                start_time: getDate(day + " " + chooseTimeBlockStartDate).valueOf(),
                end_time: getDate(day + " " + chooseTimeBlockEndDate).valueOf()
            }
        ];
        if (0 == $("#" + id).val()) {
            toastr.error("请选择患者");
            return;
        }
        mandy_put_therapist_schedule(prescriptionItemId, selectedTherapistId, patientId, timeListAdd, [],
                function (data) {
                    getPrescriptionItemList(1);
                    getGroupTherapistSchedulePeriods();
                    $('#modal-choose-patient-div').modal('hide');
                });
    }

    function filterPatient2() {
        var time = getDate(chooseTimeBlockStartDate).valueOf();

        if ($('#patient-checkbox').is(':checked')) {
            getPrescriptionItemList2(0, 1, 10000);
        }
        else {
            getPrescriptionItemList2(null, 1, 10000);
        }

    }

    function selectAmPm() {
        var amPm = amPmSelect.val();
        var tbodyTrs = $("#one-day-schedule-tbody tr");
        var trs = $("#one-day-schedule tr");
        $.each(trs, function (idx, tr) {
            var tds = $(tr).children('td');
            $.each(tds, function (idx, td) {
                if (idx > 0 && idx < 7) {
                    if (amPm == 'pm') {
                        $(td).addClass('hide');
                    } else {
                        $(td).removeClass('hide');
                    }
                }
                if (idx > 6) {
                    if (amPm == 'pm') {
                        $(td).removeClass('hide');
                    } else {
                        $(td).addClass('hide');
                    }
                }
            });
        });
    }

    function search() {
//        pageInit1(2);
        currentPage = 1;
        var scrollY = $(document).scrollTop();
        getPrescriptionItemList(2, scrollY);
    }

    (function ($) {
        $.fn.hoverDelay = function (options) {
            var defaults = {
                hoverDuring: 500,
                outDuring: 500,
                hoverEvent: function () {
                    $.noop();
                },
                outEvent: function () {
                    $.noop();
                }
            };
            var sets = $.extend(defaults, options || {});
            var hoverTimer, outTimer;
            return $(this).each(function () {
                $(this).hover(function () {
                    clearTimeout(outTimer);
                    hoverTimer = setTimeout(sets.hoverEvent, sets.hoverDuring);
                }, function () {
                    clearTimeout(hoverTimer);
                    outTimer = setTimeout(sets.outEvent, sets.outDuring);
                });
            });
        }
    })(jQuery);

    function buildAddVacationDiv() {
        vacationRemark.val("");
        vacationMedical.prop("disabled", false);

        vacationType.prop("checked", false);
        vacationDate.val(new Date().format("yyyy-MM-dd"));
        timeSlider.noUiSlider.set(["9:00", "17:00"]);
        vacationRepeat.val("0");
        $("#vacation-btn").attr("onclick", "addVacation()");
    }

    function buildUpdateVacationDiv(vacation, event) {
        var startTime = new Date(vacation.start_time).format("HH:mm");
        var endTime = new Date(vacation.end_time).format("HH:mm");
        vacationRemark.val(vacation.remark);


        vacationMedical.val(vacation.medical.id);
        vacationMedical.prop("disabled", true);

        vacationDate.val(new Date(vacation.date).format("yyyy-MM-dd"));
        timeSlider.noUiSlider.set([startTime, endTime]);
        if (vacation.loop_weekday == null) {
            vacationRepeat.val("0");
        } else {
            vacationRepeat.val("1");
        }

        if (startTime == "08:00" && endTime == "18:00") {
            vacationType.prop("checked", true);
        } else {
            vacationType.prop("checked", false);
        }
        $("#vacation-btn").attr("onclick", "updateVacation(" + vacation.id + ")");
    }

    function addVacation() {
        if (vacationRemark.val() == null || vacationRemark.val() == "") {
            toastr.error("请填写标题！");
            return;
        }else if (vacationRemark.val().length > 15){
            toastr.error("标题请勿超过15个字！");
            return;
        }
        if (vacationMedical.val() == null) {
            toastr.error("请选择一名治疗师！");
            return;
        }
        var times = timeSlider.noUiSlider.get();
        var sdate = getDate(vacationDate.val() + " " + times[0]);
        var edate = getDate(vacationDate.val() + " " + times[1]);

        mandy_add_vacation(vacationMedical.val(), vacationRemark.val(), vacationRepeat.val() == "1", sdate.getTime(),
                edate.getTime(),
                function (date) {
                    toastr.success("添加成功！");
                    $('#modal-add-vacation-div').modal('hide');
                    getGroupTherapistSchedulePeriods();
                });
    }

    function updateVacation(vacationId) {
        if (vacationRemark.val() == null || vacationRemark.val() == "") {
            toastr.error("请填写标题！");
            return;
        }

        var times = timeSlider.noUiSlider.get();
        var sdate = getDate(vacationDate.val() + " " + times[0]);
        var edate = getDate(vacationDate.val() + " " + times[1]);

        mandy_put_vacation(vacationId, vacationRemark.val(), vacationRepeat.val() == "1", sdate.getTime(), edate.getTime(), function (date) {
            toastr.success("修改成功！");
            $('#modal-add-vacation-div').modal('hide');
            getGroupTherapistSchedulePeriods();
        });
    }

    function delVacation(vaId) {
        mandy_delete_vacation(vaId, function (data) {
            toastr.success("删除成功！");
            getGroupTherapistSchedulePeriods();
        });
    }

</script>

</body>


</html>